package com.sgb.kjwl.viewmodel.transport;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Point;
import android.location.LocationManager;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.DriveStep;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.sgb.alimaplibrary.MarkerEntity;
import com.sgb.capital.view.widget.MToast;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.home.MapSourceEntity;
import com.sgb.kjwl.model.entity.home.MapSourceSearchEntity;
import com.sgb.kjwl.model.entity.transport.CarTypeAndCarLength;
import com.sgb.kjwl.model.entity.transport.CheckStateEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.OperateGoodsSourcePlaceVO;
import com.swgk.core.view.entity.PermissionEntity;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.link.utils.LocationUtil;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.ScreenUtil;
import com.swgk.core.util.SharedPreferenceUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sgb.kjwl.view.widget.GoodsMoreFilterPopWindow.DEFAULT_GOODS_TYPE;

/**
 * Describe:
 * Author:
 * Date:    2021/8/16
 */
public class MapFindingSourceModel extends AndroidViewModel {
    private Context mContext;
    public MutableLiveData<Boolean> ldUnfold = new MutableLiveData<>();//折贴

    //装卸点经纬度信息
    private List<LatLonPoint> sourcePoints = new ArrayList<>();
    //货源信息标记集合
    private List<MarkerOptions> markerOptions = new ArrayList<>();
    private RouteSearch planRouteSearch;
    public OperateGoodsSourcePlaceVO place;

    public MapFindingSourceModel(@NonNull @NotNull Application application) {
        super(application);
        this.mContext = application;
    }

    //地图缩放级别
    public float zoomLevel = 15f;
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldGoodsType = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarLen = new MutableLiveData<>();
    public MutableLiveData<Integer> ldCurrSource = new MutableLiveData<>();
    public MutableLiveData<Integer> ldSearchResult = new MutableLiveData<>();
    public MutableLiveData<Boolean> ldIsClickMarker = new MutableLiveData<>();
    public MutableLiveData<List<CarTypeAndCarLength>> ldCarTypeMore = new MutableLiveData<>();
    public MutableLiveData<List<CarInfo>> ldRefreshCar = new MutableLiveData<>();
    public MutableLiveData<CheckStateEntity> checkSourceLD = new MutableLiveData<>();
    public MutableLiveData<PermissionEntity> setUserInfo = new MutableLiveData<>();

    //屏幕高度
    private int mScreenWidth;
    //货源信息标记集合
    private List<Marker> markers = new ArrayList<>();
    private List<LatLng> latLngs = new ArrayList<>();//经纬度集合
    private AMap aMap;
    public int lastPosition;
    public Marker markerLast;
    private LatLng currLatLng;//当前搜索的中心点
    public List<MapSourceEntity> sources = new ArrayList<>();//当前地图上展示的车辆信息集合
    public List<MarkerEntity> markerEntityList = new ArrayList<>();

    /**
     * 用于控制地图滑动监听
     */
    public MutableLiveData<Boolean> ldAddChangeListener = new MutableLiveData<>();
    private Handler mHandler = new Handler(msg -> {
        ldAddChangeListener.postValue(true);
        return false;
    });

    public List<MapSourceEntity> getSources() {
        return sources;
    }

    public void setSources(List<MapSourceEntity> sources) {
        this.sources = sources;
    }

    /**
     * 地图找货
     */
    public void findSourceByMap(Activity activity, MapSourceSearchEntity searchEntity) {
        DialogHelper.showProgressDialog(activity, "请求中...");
        if (searchEntity.getSearchLatitude() > 0 && searchEntity.getSearchLongitude() > 0) {
            currLatLng = new LatLng(searchEntity.getSearchLatitude(), searchEntity.getSearchLongitude());
            moveMap(searchEntity.getSearchLatitude(), searchEntity.getSearchLongitude());
        } else
            return;

        Map map = new HashMap();
        map.put("keyWord", "");
        map.put("limit", 200);
        map.put("page", 1);
        map.put("needVideo", "0");
        if (TextUtils.isEmpty(searchEntity.getShipmentEndTime())) {
            map.put("shipmentEndTime", "");
        } else {
            map.put("shipmentEndTime", Long.valueOf(searchEntity.getShipmentEndTime()));
        }
        if (!TextUtils.isEmpty(searchEntity.getShipmentTime())) {
            map.put("shipmentTime", Long.valueOf(searchEntity.getShipmentTime()));
        } else {
            map.put("shipmentTime", "");
        }

        if (LocationUtil.isOpenLocation(mContext)) {
            if (LocationUtil.getCurrentLongitude() != 0.00) {
                map.put("ipLongitude", LocationUtil.getCurrentLongitude());
                map.put("ipLatitude", LocationUtil.getCurrentLatitude());
            }
        }

        if (TextUtils.isEmpty(searchEntity.getGoodsModeNos()) || searchEntity.getGoodsModeNos().equals(DEFAULT_GOODS_TYPE)) {
            map.put("goodsTypeNo", "");
        } else {
            map.put("goodsTypeNo", searchEntity.getGoodsModeNos());
        }

        if (searchEntity.getRadius() > 0) {
            map.put("radius", searchEntity.getRadius());
        } else {
            map.put("radius", 0);
        }

        map.put("searchLongitude", searchEntity.getSearchLongitude());
        map.put("searchLatitude", searchEntity.getSearchLatitude());
        map.put("destProvinceNo", searchEntity.getDestProvinceNo());
        map.put("destCityNo", searchEntity.getDestCityNo());
        map.put("destDistrictNo", searchEntity.getDestDistrictNo());

        if (TextUtils.isEmpty(searchEntity.getMinWeight())) {
            map.put("minWeight", 0);
        } else {
            map.put("minWeight", Double.valueOf(searchEntity.getMinWeight()));
        }

        if (TextUtils.isEmpty(searchEntity.getMaxWeight()) || searchEntity.getMaxWeight().startsWith("99999")) {
            map.put("maxWeight", 0);
        } else {
            map.put("maxWeight", Double.valueOf(searchEntity.getMaxWeight()));
        }

        map.put("carTypeNos", searchEntity.getCarTypeNos());
        map.put("carLenNos", searchEntity.getCarLenNos());

        NewAPIManager.getInstance().getLogisticsAPI().getMapFindSource(map).enqueue(new ICallBack<BaseEntity<ProListEntity<List<MapSourceEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ProListEntity<List<MapSourceEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.getData() == null || response.getData() == null)
                    return;
                if (response.getData().getList() != null && response.getData().getList().size() > 0) {
                    loadMarkerInfo(response.getData().getList());
                    ldSearchResult.postValue(response.getData().getList().size());
                } else {
                    if (aMap != null)
                        aMap.clear();
                    if (sources != null)
                        sources.clear();
                    if (markerEntityList != null)
                        markerEntityList.clear();
                    ldSearchResult.postValue(0);
                    addLocationMarker(currLatLng);
                }
                setPlanRouteInfo(place);
            }
        });
    }

    /**
     * 获取货源类型
     */
    public void getGoodsType() {
        NewAPIManager.getInstance().getLogisticsAPI().getAllGoodsType().enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;
                if (response.body().getCode().equals("200") && response.body().getData() != null) {
                    ldGoodsType.postValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
                MToast.showToast(mContext, t.getMessage());
            }
        });

    }

    /**
     * 获取用户车辆信息
     */
    public void getCarInfo() {
        NewAPIManager.getInstance().getLogisticsAPI().getCarInfo().enqueue(new Callback<BaseEntity<List<CarInfo>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<CarInfo>>> call, Response<BaseEntity<List<CarInfo>>> response) {
                if (response.body() != null && response.body().getState().equals(APIManager.RESPONSE_OK) && response.body().getCode().equals("200")) {
                    ldRefreshCar.postValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CarInfo>>> call, Throwable t) {
                MToast.showToast(getApplication(), t.getMessage());
            }
        });
    }


    /**
     * 车型车长
     *
     * @param goodsTypeNo 货物类型No（多个逗号分隔）
     */
    public void getCarTypeAndCarLengthList(String goodsTypeNo) {
        if (TextUtils.isEmpty(goodsTypeNo) || goodsTypeNo.equals(DEFAULT_GOODS_TYPE)) {
            goodsTypeNo = "";
        }
        NewAPIManager.getInstance().getLogisticsAPI().getCarTypeAndLengthList(goodsTypeNo).enqueue(new Callback<BaseEntity<List<CarTypeAndCarLength>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<CarTypeAndCarLength>>> call, Response<BaseEntity<List<CarTypeAndCarLength>>> response) {
                if (response.body() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK) && response.body().getCode().equals("200")) {
                    ldCarTypeMore.postValue(response.body().getData());
                } else {
                    MToast.showToast(getApplication(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CarTypeAndCarLength>>> call, Throwable t) {
                MToast.showToast(getApplication(), t.getMessage());
            }
        });
    }

    public void setAMap(AMap aMap) {
        this.aMap = aMap;
        //添加marker点击监听
        aMap.setOnMarkerClickListener(marker -> {
            if (marker.getObject() != null) {
                MapSourceEntity item = (MapSourceEntity) marker.getObject();

                for (int i = 0; i < sources.size(); i++) {
                    if (item.getNo().equals(sources.get(i).getNo())) {
                        setMarkStyle(i, marker, true);
                        if (lastPosition != 0) {
                            resetMarker(marker.getId(), marker, lastPosition);
                        }
                        markerLast = marker;
                        lastPosition = i;

                        ldIsClickMarker.postValue(true);
                        ldCurrSource.postValue(i);
                        markerLast = marker;
                        lastPosition = i;
                        break;
                    }
                }

            } else {
                return true;//不显示在中心
            }
            return false;
        });
    }

    /**
     * 加载地图 Marker 信息
     */
    public void loadMarkerInfo(List<MapSourceEntity> carEntities) {
        if (aMap == null || carEntities == null || carEntities.size() <= 0)
            return;
        aMap.clear();
        latLngs.clear();
        sources.clear();
        markerEntityList.clear();
        lastPosition = 0;

        if (currLatLng != null) {
            latLngs.add(currLatLng);
        }

        for (int i = 0; i < carEntities.size(); i++) {
            MapSourceEntity infoEntity = carEntities.get(i);
            if (infoEntity.getLatitude() > 0 && infoEntity.getLongitude() > 0) {
                sources.add(infoEntity);
                latLngs.add(new LatLng(infoEntity.getLatitude(), infoEntity.getLongitude()));

                LatLng latLng = new LatLng(infoEntity.getLatitude(), infoEntity.getLongitude());
                MarkerEntity markerEntity;
                markerEntity = new MarkerEntity(latLng, getMarkerView(infoEntity, false), null);
                markerEntityList.add(markerEntity);
            }
        }
        //添加所有marker
        addMarkers(carEntities);
    }

    public View getMarkerView(MapSourceEntity entity, boolean isBigMarkView) {
        View markerView = LayoutInflater.from(mContext).inflate(R.layout.view_marker_goods_source, null);
        TextView freight = markerView.findViewById(R.id.tv_marker_freight);
        TextView destination = markerView.findViewById(R.id.tv_marker_destination);
        if (entity.getFreightType() != null && !entity.getFreightType().equals("0")) {
            freight.setText("电议");
        } else {
            freight.setText(String.format("%s%s", NumberUtil.trim0(entity.getFreight()), entity.getFreightUnit()));
        }
        String des = entity.getDestCityName() + entity.getDestDistrictName();
        if (des.length() > 5) {
            destination.setText(des.substring(0, 4) + "...");
        } else {
            destination.setText(des);
        }
        if (entity.getPattern() != null && entity.getPattern().equals("1")) {
            if (isBigMarkView) {
                markerView.setBackgroundResource(R.mipmap.bg_goods_marker_select);
            } else {
                markerView.setBackgroundResource(R.mipmap.bg_goods_marker_normal);
            }
        } else {
            if (isBigMarkView) {
                markerView.setBackgroundResource(R.mipmap.bg_bidding_marker_select);
            } else {
                markerView.setBackgroundResource(R.mipmap.bg_bidding_marker_normal);
            }
        }
        return markerView;
    }

    public void addMarkers(List<MapSourceEntity> carEntities) {
        markers.clear();

        for (int i = 0; i < markerEntityList.size(); i++) {
            Marker marker = aMap.addMarker(getMarkerOptions(markerEntityList.get(i)));
            marker.setObject(carEntities.get(i));
        }
    }

    public MarkerOptions getMarkerOptions(MarkerEntity markerEntity) {
        BitmapDescriptor bitmapSmall;
        if (markerEntity.getIcon() == 0 && markerEntity.getView() != null) {
            bitmapSmall = BitmapDescriptorFactory.fromView(markerEntity.getView());
        } else {
            bitmapSmall = BitmapDescriptorFactory.fromResource(markerEntity.getIcon());
        }
        MarkerOptions markerOption = new MarkerOptions()
                .position(markerEntity.getLatLng())
                .title(markerEntity.getTitle())
//                .snippet(markerEntity.getSnippet())
                .icon(bitmapSmall)
                .draggable(false);
        return markerOption;
    }

    public void resetMarkersSmall() {
        if (markers != null && markers.size() > 0) {
            for (int i = 0; i < markers.size(); i++) {
                setMarkStyle(i, markers.get(i), false);
            }
        }
    }

    // 设置maker大小图标
    private void setMarkStyle(int pos, Marker marker, boolean isBigMarkView) {
        MapSourceEntity entity = sources.get(pos);
        BitmapDescriptor bitmapSmall = null;
        bitmapSmall = BitmapDescriptorFactory.fromView(getMarkerView(entity, isBigMarkView));
        marker.setIcon(bitmapSmall);
    }

    private void resetMarker(String curMarkerId, Marker markerNew, int pos) {
        MapSourceEntity entity = sources.get(pos);
        if (null != markerLast) {
            if (!TextUtils.equals(curMarkerId, markerLast.getId())) {
                markerLast.setIcon(BitmapDescriptorFactory.fromView(getMarkerView(entity, false)));
            }
        }
    }

    public void moveMap(double lat, double lng) {
        if (aMap != null) {
            ldAddChangeListener.postValue(false);
            mHandler.removeMessages(1);
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), zoomLevel));
            mHandler.sendEmptyMessageDelayed(1, 200);
        }
    }

    /**
     * 将视图移到定位或者装车点
     *
     * @param latLng
     */
    public void addLocationMarker(LatLng latLng) {
        if (aMap == null)
            return;
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_location_blue));
        aMap.addMarker(markerOption);
    }

    /**
     * 手机是否开启位置服务，如果没有开启那么所有app将不能使用定位功能
     */
    public boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    /**
     * 获取屏幕中心的经纬度坐标
     *
     * @param mMapView
     * @return
     */
    public LatLng getMapCenterPoint(MapView mMapView) {
        int left = mMapView.getLeft();
        int top = mMapView.getTop();
        int right = mMapView.getRight();
        int bottom = mMapView.getBottom();
        // 获得屏幕中心点的位置
        int x = (int) (mMapView.getX() + (right - left) / 2);
        int y = (int) (mMapView.getY() + (bottom - top) / 2);
        Projection projection = mMapView.getMap().getProjection();
        LatLng pt = projection.fromScreenLocation(new Point(x, y));
        return pt;
    }

    /**
     * 计算当前半径
     */
    public String calculateCurrentRadius() {
        if (aMap == null)
            return "1110.85";
        //计算并设置设置当前半径(单位：米)
        if (mScreenWidth == 0) {
            mScreenWidth = ScreenUtil.getDisplayWidth();
        }
        //屏幕高度的一半 * 当前缩放1px代表的米数
        String radius = NumberUtil.trim0(mScreenWidth / 2f * aMap.getScalePerPixel());
        return radius;
    }


    /**
     * 检验货源状态
     *
     * @param no
     */
    public void goodsSourceStatusCheck(String no) {
        NewAPIManager.getInstance().getLogisticsAPI().goodsSourceStatusCheck(no).enqueue(new Callback<BaseEntity<CheckStateEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<CheckStateEntity>> call, Response<BaseEntity<CheckStateEntity>> response) {
                if (response.body() == null) return;
                if (response.body().getState().equals("ok") && response.body().getData() != null) {
                    CheckStateEntity stateEntity = response.body().getData();
                    stateEntity.setNo(no);
                    checkSourceLD.postValue(stateEntity);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<CheckStateEntity>> call, Throwable t) {
            }
        });
    }

    /**
     * 获取用户物流权限
     *
     * @param context
     */
    public void getLogisticsPermissions(Context context) {
        DialogHelper.showProgressDialog(context, "加载中");
        NewAPIManager.getInstance().getLogisticsAPI().getLogisticsPermissions().enqueue(new ICallBack<BaseEntity<PermissionEntity>>() {
            @Override
            public void onSuccess(BaseEntity<PermissionEntity> data) {
               if(data.isSuccess()){
                   SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, data.getData().getUserType());
                   UserOperating.getInstance().setUserInfo(data.getData());
                   setUserInfo.postValue(data.getData());
               }
            }
        });
    }


    /**
     * 预置路径信息
     */
    public void setPlanRouteInfo(OperateGoodsSourcePlaceVO place) {
        //装载 装卸地经纬度
        if (place != null && place.getDestLatitude() != 0 && place.getDestLongitude() != 0) {
            this.place = place;
            aMap.clear();

            markerEntityList.clear();
            for (int i = 0; i < sources.size(); i++) {
                MapSourceEntity infoEntity = sources.get(i);
                if (infoEntity.getLatitude() > 0 && infoEntity.getLongitude() > 0) {
                    LatLng latLng = new LatLng(infoEntity.getLatitude(), infoEntity.getLongitude());
                    MarkerEntity markerEntity;
                    markerEntity = new MarkerEntity(latLng, getMarkerView(infoEntity, false), null);
                    markerEntityList.add(markerEntity);
                }
            }
            addMarkers(sources);
            markerOptions.clear();
            LatLonPoint sendPoint = null;
            LatLng sendLL = null;
            if (place.getLatitude() > 0 && place.getLongitude() > 0) {
                sendPoint = new LatLonPoint(place.getLatitude(), place.getLongitude());
                sendLL = new LatLng(place.getLatitude(), place.getLongitude());
            }

            LatLonPoint destPoint = null;
            LatLng destLL = null;
            if (place.getDestLatitude() > 0 && place.getDestLongitude() > 0) {
                destPoint = new LatLonPoint(place.getDestLatitude(), place.getDestLongitude());
                destLL = new LatLng(place.getDestLatitude(), place.getDestLongitude());
            }

            sourcePoints.clear();
            sourcePoints.add(sendPoint);
            sourcePoints.add(destPoint);

            //起点
            markerOptions.add(createMarker(sendLL, 1));
            //终点
            markerOptions.add(createMarker(destLL, 2));
            planningLoadingRoute(sourcePoints, 1);
        }
    }


    /**
     * 添加需要规划的路线数据，并开启异步查询
     *
     * @param points 路线连接点
     * @param type   规划路线的类型：1——计划，2——实际
     */
    public void planningLoadingRoute(List<LatLonPoint> points, int type) {
        //路线点不能少于两个
        if (points == null || points.size() < 2) {
            return;
        }
        List<LatLonPoint> passedByPoints = null;
        //设置开始位置坐标点(注意经纬度不能写反,会报错1800(只能规划到中国区域里的地图路线))
        LatLonPoint startPoint = points.get(0);
        //设置目的地坐标点
        LatLonPoint endPoint = points.get(points.size() - 1);
        //查询信息对象
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint, endPoint);

        if (points.size() > 2) {
            passedByPoints = new ArrayList<>();
            for (int i = 1; i < points.size() - 1; i++) {
                passedByPoints.add(points.get(i));
            }
        }
        //设置搜索参数 1.fromAndTo 路径的起点终点  2.路径规划的策略（可选），默认为“躲避拥堵” 3.途经点，可选 4.避让区域，可选， 5.货车大小 ,默认轻型车
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(
                fromAndTo,
                RouteSearch.DRIVING_SINGLE_SHORTEST,
                passedByPoints,
                null,
                "");

        if (type == 1) {
            if (planRouteSearch == null)
                planRouteSearch = new RouteSearch(mContext);
            // 搜索监听
            planRouteSearch.setRouteSearchListener(new OnPlanListener());
            //开始异步查询
            planRouteSearch.calculateDriveRouteAsyn(query);
        }
    }


    /**
     * 路线规划回调类
     */
    private class OnPlanListener implements RouteSearch.OnRouteSearchListener {

        @Override
        public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

        }

        @Override
        public void onDriveRouteSearched(DriveRouteResult result, int code) {
            if (code == 1000 && result != null && result.getPaths() != null && result.getPaths().size() > 0) {
                if (aMap == null) {
                    return;
                }

                List<DrivePath> paths = result.getPaths();
                //创建存储坐标点的集合
                List<LatLonPoint> latLonPoints = new ArrayList<>();
                List<LatLng> planLatLngs = new ArrayList<>();

                //遍历获取规划的所有路线坐标点
                for (DriveStep mDriveStep : paths.get(0).getSteps()) {
                    for (LatLonPoint mLatLonPoint : mDriveStep.getPolyline()) {
                        latLonPoints.add(mLatLonPoint);
                        latLngs.add(new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()));
                        planLatLngs.add(new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()));
                    }
                }

                //无纹理纯色路线
//                DrivePath drivePath = paths.get(0);
//                PlanRouteOverlay overlay = new PlanRouteOverlay(context, aMap, drivePath,
//                        result.getStartPos(), result.getTargetPos(), latLonPoints);
//                overlay.setThroughPointIconVisibility(false);//隐藏途径点
//                overlay.setNodeIconVisibility(false);//设置节点marker是否显示
//                overlay.setIsColorfulline(false);//是否用颜色展示交通拥堵情况，默认true
//                overlay.addToMap();
//                overlay.zoomToSpan();

                //带纹理纯色路线
                aMap.addPolyline(new PolylineOptions()
                        //路线坐标点的集合
                        .addAll(planLatLngs)
                        //线的宽度
                        .width(20)
                        .setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.map_alr))
                );
                ldUnfold.postValue(true);

                //添加所有marker
                for (MarkerOptions sourceMarker : markerOptions) {
                    aMap.addMarker(sourceMarker);
                }

                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(new LatLngBounds(
                        new LatLng(result.getStartPos().getLatitude(), result.getStartPos().getLongitude()),
                        new LatLng(result.getTargetPos().getLatitude(), result.getTargetPos().getLongitude())), 50));
            } else {
                MLog.d("api", "路线规划失败");
            }
        }

        @Override
        public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

        }

        @Override
        public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

        }
    }


    private MarkerOptions createMarker(LatLng latLng, int type) {
        int resource = 0;
        switch (type) {
            case 1:
                resource = R.mipmap.icon_samll_handle;
                break;
            case 2:
                resource = R.mipmap.icon_unload;
                break;
        }
        BitmapDescriptor markIcon = BitmapDescriptorFactory.fromResource(resource);
        return new MarkerOptions().position(latLng).icon(markIcon);
    }
}
